#include "socket_class.hpp"
#include "acceptor.hpp"
#include "network.hpp"
#include "tcp_link.hpp"
#include "tlv_type.h"
#include "io.hpp"
#include <shadow.h>
#include <iostream>

using std::cout;
using std::endl;

void test()
{
    //初始化服务端
    rocket::acceptor server(10086,"127.0.0.1");
    //启动服务端
    server.start();
    cout<<"listening"<<endl;

    //接收客户端链接
    rocket::tcp_link link1( server.accept());
    cout<<"someone linked"<<endl;

    rocket::packet user;
    //接收客户端的用户名
    int ret=link1.read_packet(user);
    cout<<"receive :"<<ret<<":"<<endl;
    user.print();
    //判断该数据type是否为LOGIN_USER
    if (user.get_type() == rocket::LOGIN_USER) 
    {
	    cout << "type=LOGIN_USER" << endl;
        //根据用户名获取密文盐值等相关内容
	    spwd *pna = getspnam(user.get_data().c_str());

	    //从字符串中分离出盐值
	    if (pna != NULL) 
        {
		    int salt_length = 0;
		    for (int i = 0, j = 0; i < strlen(pna->sp_pwdp); ++i) 
            {
			    if (pna->sp_pwdp[i] == '$') 
                {
				    ++j;
				    if (j == 4) 
                    {
					    salt_length = i;
					    break;
				    }
			    }
		    }
            char salt[1024] = { 0 };
	        strncpy(salt, pna->sp_pwdp, salt_length);

	        rocket::tlv salt_tlv(rocket::LOGIN_SALT, strlen(salt),salt);
            //发送盐值给客户端
	        ret=link1.send_tlv(salt_tlv);
	        cout << "send_salt_tlv :"<<ret<<" :";
	        salt_tlv.print();
	    }
        rocket::packet ciphertext;

        //接收来自客户端的密文
        ret=link1.read_packet(ciphertext);
        cout<<"receive ciphertext :"<<ret<<" : ";
        ciphertext.print();
        //判断接收到数据type是否为LOGIN_CIPHERTEXT
        if(ciphertext.get_type()==rocket::LOGIN_CIPHERTEXT)
        {
            cout<<"type=LOGIN_CIPHERTEXT"<<endl;
            //判断密文是否匹配,并向客户端发送密文匹配结果
            if(strcmp(ciphertext.get_data().c_str(), pna->sp_pwdp)==0)
            {
                cout<<"OK"<<endl;
                rocket::tlv result_tlv(rocket::LOGIN_RESULT,strlen("success"),"success");
                ret=link1.send_tlv(result_tlv);
	            cout << "send_salt_tlv :"<<ret<<" :";
	            result_tlv.print();
            }
            else
            {
                cout<<"NO"<<endl;
                rocket::tlv result_tlv(rocket::LOGIN_RESULT,strlen("success"),"success");
                ret=link1.send_tlv(result_tlv);
	            cout << "send_salt_tlv :"<<ret<<" :";
	            result_tlv.print();
            }
        }
    }


}

int main()
{
    test();
    return 0;
}

